package logic

import (
	"context"
	"gitee.com/Cauchy_AQ/vxopen/model/redis"
	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/internal/errors"
	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/internal/svc"
	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/transform"

	"github.com/zeromicro/go-zero/core/logx"
)

type CaptchaWithIpLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCaptchaWithIpLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CaptchaWithIpLogic {
	return &CaptchaWithIpLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CaptchaWithIpLogic) CaptchaWithIp(in *transform.CaptchaWithIpReq) (*transform.CaptchaWithIpResp, error) {
	captchaWithIpResp := &transform.CaptchaWithIpResp{Ok: false}
	ip := redis.CacheCaptchaIpPrefix + in.Ip
	exists, err := l.svcCtx.RDB.Exists(context.Background(), ip).Result()
	if err != nil {
		return captchaWithIpResp, err
	}
	if exists == 1 {
		return captchaWithIpResp, errors.ErrorCaptchaIpExists
	}
	// ip not exist
	if err = l.svcCtx.RDB.Set(context.Background(), ip, true, redis.CacheCaptchaIpTimeout).Err(); err != nil {
		return captchaWithIpResp, err
	}
	captchaWithIpResp.Ok = true
	return captchaWithIpResp, nil
}
